package org.springblade.modules.enterprise.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.enterprise.entity.PolicyInfo;
import org.springblade.modules.enterprise.service.IPolicyApplyService;
import org.springblade.modules.enterprise.service.IPolicyInfoService;
import org.springblade.modules.enterprise.vo.PolicyInfoVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.time.Duration;
import java.util.Date;

@AllArgsConstructor
@Api(value = "政策信息", tags = "(api)政策信息")
@RestController
@RequestMapping("/enterprise/policy-apply")
public class PolicyApplyApi {

	private IPolicyInfoService policyInfoService;

	private IPolicyApplyService policyApplyService;

	@ApiOperation(value = "获取所有政策信息", notes = "")
	@GetMapping("list")
	public R getAllPolicyInfo(PolicyInfoVO policyInfo, Query query) {
		IPage<PolicyInfoVO> pages = policyInfoService.selectPolicyInfoWithApplyStatus(Condition.getPage(query), policyInfo);
		// 3.设置剩余天数和政策申请ID
		setExcessTimeAndPolicyApplyId(pages);
		return R.data(pages);
	}

	private void setExcessTimeAndPolicyApplyId(IPage<PolicyInfoVO> pageVO) {
		pageVO.getRecords().forEach(policyInfoVO -> {
			// 计算政策申请剩余时间.
			Date nowTime = new Date();
			Date expireTime = policyInfoVO.getExpireTime();
			// 由于存储日期时间时00:00 就算剩余时间时给它加1天
			expireTime = DateUtil.plusDays(expireTime, 1);
			Duration duration = Func.between(nowTime, expireTime);
			policyInfoVO.setExcessTime(duration.toDays());
		});
	}

	@ApiOperation(value = "获取政策详情", notes = "")
	@GetMapping("detail")
	public R getPolicyInfo(PolicyInfo policyInfo) {
		// getOne具体实现已被重写(查看ServiceImpl)
		PolicyInfoVO detail = (PolicyInfoVO) policyInfoService.getOne(Condition.getQueryWrapper(policyInfo));
		return R.data(detail);
	}
}
